package com.jie.ribbonconsumer.service;

import com.jie.ribbonconsumer.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Random;

/**
 * @author jie
 * @date 2019/8/2 -10:41
 */
@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloFallback")
    public String helloService() throws InterruptedException {
        //使用 ignoreExceptions 属性 Hystrix 会将它包装在 HystrixBadRequestException 中抛出
//        int i = 1 / 0;
        int sleepTime = new Random().nextInt(3000);
        Thread.sleep(sleepTime);
        return restTemplate.getForObject("http://hello-service/hello", String.class);
    }


    public User getUserById(Integer id) {
        return restTemplate.getForObject("http://hello-service/users/{1}", User.class,id);
    }

    public String helloFallback() {
        return "error";
    }
}
